'use strict';

/* Controllers */

angular.module('app')
    .controller('AppCtrl', ['$scope', '$localStorage', '$window', '$state', '$modal',
        function ($scope, $localStorage, $window, $state, $modal) {
            $scope.state = $state;
            // add 'ie' classes to html
            var isIE = !!navigator.userAgent.match(/MSIE/i);
            if (isIE) { angular.element($window.document.body).addClass('ie'); }
            if (isSmartDevice($window)) { angular.element($window.document.body).addClass('smart') }

            // config
            $scope.app = {
                name: window.appInfo.name,
                version: '1.0.0',
                // for chart colors
                color: {
                    primary: '#7266ba',
                    info: '#23b7e5',
                    success: '#27c24c',
                    warning: '#fad733',
                    danger: '#f05050',
                    light: '#e8eff0',
                    dark: '#3a3f51',
                    black: '#1c2b36'
                },
                settings: {
                    themeID: 1,
                    navbarHeaderColor: 'bg-black',
                    navbarCollapseColor: 'bg-black',
                    asideColor: 'bg-white b-r',
                    headerFixed: true,
                    asideFixed: false,
                    asideFolded: false,
                    asideDock: false,
                    container: true
                },
                ip:""
            };
            // save settings to local storage
            if (angular.isDefined($localStorage.settings)) {
                $scope.app.settings = $localStorage.settings;
            } else {
                $localStorage.settings = $scope.app.settings;
            }
            $scope.$watch('app.settings', function () {
                if ($scope.app.settings.asideDock && $scope.app.settings.asideFixed) {
                    // aside dock and fixed must set the header fixed.
                    $scope.app.settings.headerFixed = true;
                }
                // for box layout, add background image
                // $scope.app.settings.container ? angular.element('html').addClass('bg') : angular.element('html').removeClass('bg');
                // save to local storage
                $localStorage.settings = $scope.app.settings;
            }, true);


            function isSmartDevice($window) {
                // Adapted from http://www.detectmobilebrowsers.com
                var ua = $window['navigator']['userAgent'] || $window['navigator']['vendor'] || $window['opera'];
                // Checks for iOs, Android, Blackberry, Opera Mini, and Windows mobile devices
                return (/iPhone|iPod|iPad|Silk|Android|BlackBerry|Opera Mini|IEMobile/).test(ua);
            }

            $scope.modalInfo = function (title, content, isCancel) {
                var modalInstance = $modal.open({
                    templateUrl: '/tpl/modal/info.html',
                    controller: 'AppCtrl.info',
                    size: null,
                    resolve:{
                        title:function(){
                            return title;
                        },
                        content:function(){
                            return content;
                        },
                        isCancel:function(){
                            return (typeof isCancel === "boolean" ? isCancel : true);
                        }
                    }
                });
                modalInstance.result.then(function () {
                    // console.log(userInfo,'---');
                }, function () {});
            };
        }])
    .controller('AppCtrl.info', ['$scope', '$modalInstance', 'title', 'content', 'isCancel', function($scope, $modalInstance, title, content, isCancel) {
        $scope.title = title;
        $scope.content = content;
        $scope.isCancel = isCancel;
        $scope.ok = function () {
            $modalInstance.close();
        };
        $scope.cancel = function () {
            $modalInstance.dismiss('cancel');
        };
    }])
    .factory('user_info', ['$q', '$rootScope', '$state', '$http', function ($q, $rootScope, $state, $http) {
        return {
            get: function () {
                var deferred = $q.defer();
                if (angular.isDefined(window.appInfo.user)) {
                    // if (!angular.isDefined($rootScope.userInfo)) {
                    $rootScope.userPackList = window.appInfo.userPackList;
                    $rootScope.userInfo = window.appInfo.user;
                    $rootScope.logout = function () {
                        $http.get('/app/api/logout')
                            .then(function (response) {
                                delete window.appInfo.user;
                                $state.go('access.signin');
                            }, function (x) {

                            });
                    };
                    // }
                    deferred.resolve({ userInfo: $rootScope.userInfo, userPackList: $rootScope.userPackList });
                } else {
                    deferred.resolve(null);
                }
                return deferred.promise;
            },
            check: function (scope) {
                return this.get().then(function (data) {
                    var deferred = $q.defer();
                    switch ($state.current.name) {
                        case "access.signin":
                            if (data) {
                                if (!data.userInfo) {
                                    deferred.resolve(null);
                                } else if (!data.userInfo.first) {
                                    $state.go('app.dashboard');
                                    deferred.reject(null);
                                } else if (data.userInfo.first) {
                                    $state.go('access.info');
                                    deferred.reject(null);
                                } else {
                                    deferred.resolve(null);
                                }
                            } else {
                                deferred.resolve(null);
                            }
                            break;
                        case "access.info":
                            if (data) {
                                if (!data.userInfo) {
                                    $state.go('access.signin');
                                    deferred.reject(null);
                                } else if (!data.userInfo.first) {
                                    $state.go('app.dashboard');
                                    deferred.reject(null);
                                } else {
                                    deferred.resolve(null);
                                }
                            } else {
                                $state.go('access.signin');
                                deferred.reject(null);
                            }
                            break;
                        default:
                            if (data) {
                                if (!data.userInfo) {
                                    $state.go('access.signin');
                                    deferred.reject(null);
                                } else if (data.userInfo.first) {
                                    $state.go('access.info');
                                    deferred.reject(null);
                                } else {
                                    scope.userInfo = data.userInfo;
                                    scope.userPackList = data.userPackList;
                                    deferred.resolve(null);
                                }
                            } else {
                                $state.go('access.signin');
                                deferred.reject(null);
                            }
                    }
                    return deferred.promise;
                })

            },
            set: function (obj) {
                console.log(obj);
                window.appInfo.user = obj;
                $rootScope.userInfo = obj;
                $rootScope.$broadcast("update_user_info", $rootScope.userInfo)
            },
            setPack: function (packList) {
                window.appInfo.userPackList = packList;
                $rootScope.userPackList = packList;
                $rootScope.$broadcast("update_user_pack_list", $rootScope.userPackList)
            },
            setSinglePack: function (index, packInfo) {
                window.appInfo.userPackList[index] = packInfo;
                $rootScope.userPackList = window.appInfo.userPackList;
                $rootScope.$broadcast("update_user_pack_list", $rootScope.userPackList)
            }
        };
    }
    ])
    .factory('modal_warning', ['$q', '$rootScope', '$modal', function ($q, $rootScope, $modal) {
        return {
            confirm: function (title, content, isCancel) {
                var deferred = $q.defer();
                var modalInstance = $modal.open({
                    templateUrl: '/tpl/modal/info.html',
                    controller: 'AppCtrl.info',
                    size: null,
                    resolve:{
                        title:function(){
                            return title;
                        },
                        content:function(){
                            return content;
                        },
                        isCancel:function(){
                            return (typeof isCancel === "boolean" ? isCancel : true);
                        }
                    }
                });
                modalInstance.result.then(function () {
                    deferred.resolve(null);
                }, function () {
                    deferred.reject(null);
                });
                return deferred.promise;
            }
        };
    }
    ]);